package com.xymc.webmgr.config.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * <p>Oracle数据源><p>
 *
 * @Version : 1.0
 * @Author : lihao
 * @Description :Oracle的数据源
 * 这里我们定义的数据源要扫描oracle对应的mapper.java包和mapper.xml目录
 * @Date : 2021/10/27 14:39
 **/
@Configuration
@MapperScan(basePackages = MyBatisConfigdb2.PACKAGE,sqlSessionFactoryRef = "db2SqlSessionFactory")
public class MyBatisConfigdb2 {

    // 精确到 db2 目录，以便跟其他数据源隔离
    static final String PACKAGE = "com.xymc.webmgr.dao.db2";
    static final String MAPPER_LOCATION = "classpath:mappers/db2/*.xml";

    @Value("${spring.datasource.db2.url}")
    private String url;

    @Value("${spring.datasource.db2.username}")
    private String user;

    @Value("${spring.datasource.db2.password}")
    private String password;

    @Value("${spring.datasource.db2.driver-class-name}")
    private String driverClass;

    @Bean(name = "db2DataSource")
    public DataSource clusterDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "db2TransactionManager")
    public DataSourceTransactionManager clusterTransactionManager() {
        return new DataSourceTransactionManager(clusterDataSource());
    }

    @Bean(name = "db2SqlSessionFactory")
    public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("db2DataSource") DataSource clusterDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(clusterDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(MyBatisConfigdb2.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }
}
